package edge.display.backend.MsgReceiver.Zmq;

import edge.display.backend.MsgHandler.QHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.zeromq.ZMQ;

/**
 * ZeroMQ订阅者
 *
 * @author Amane Hayaashi
 * @date 2020/11/1
 * @since 1.0
 */

@Component
@Configuration
public class ZmqSubscriber {

    @Value("${zmq.host}")
    private String zmqHost;
    @Value("${zmq.topic}")
    private String zmqTopic;

    public void subscribe() {
        new Thread(() -> {
            boolean feed = false;
            ZMQ.Context context = ZMQ.context(1);
            ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
            subscriber.connect(zmqHost);
            subscriber.subscribe(zmqTopic.getBytes(ZMQ.CHARSET));
            // open TCPKeepAlive
            subscriber.setTCPKeepAlive(1);
            // detect the connection in 2 minutes
            subscriber.setTCPKeepAliveIdle(120L);
            // resend the package if no response in 10s
            subscriber.setTCPKeepAliveInterval(1L);
            // three detection indicates to useless
            subscriber.setTCPKeepAliveCount(3);
            while (!Thread.currentThread().isInterrupted()) {
                String s = subscriber.recvStr();
                if (feed) {
                    QHandler.handle(s);
                }
                feed = !feed;
            }
        }).start();
    }
}
